<template>
  <div class="rolling-speed">
    <div style="height: 2vh"></div>
    <el-container>
      <el-header style="height: 10vh">
        <div class="common-div-card rs-header">
          <el-form :inline="true" :model="headerSearchForm" class="rs-header-form">
            <el-form-item label="钢种">
              <el-input v-model="headerSearchForm.gradeStr" placeholder="请输入钢种" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
              <el-button type="success" @click="handleAdd">新增</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <el-main>
        <el-row>
          <div style="width: 100%" class="common-div-card rs-table">
            <el-table
              :data="tableData"
              border
              :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
              :cell-style="{ textAlign: 'center' }"
              :stripe="true"
              v-loading="tableLoading"
              :show-overflow-tooltip="true"
            >
              <el-table-column type="index" label="序号" width="80" />
              <el-table-column prop="gradeStr" label="钢种"/>
              <el-table-column prop="minWidth" label="最小宽度(mm)" width="120px" />
              <el-table-column prop="maxWidth" label="最大宽度(mm)" width="120px" />
              <el-table-column prop="maxInclusive" label="最大包含" width="100px">
                <template #default="scope">
                  <span>{{ scope.row.maxInclusive === 1 ? '是' : '否' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="edgeTrimCond" label="切边条件" width="100px">
                <template #default="scope">
                  <span>{{ scope.row.edgeTrimCond === 1 ? '是' : '否' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="contractStr" label="合同号" width="150px" />
              <el-table-column prop="excludeContractStr" label="排除合同号" width="150px" />
              <el-table-column prop="levelStr" label="等级" width="120px" />
              <el-table-column prop="speedLimit" label="速度限制" width="100px" />
              <el-table-column prop="enabled" label="启用状态" width="100px">
                <template #default="scope">
                  <el-tag :type="scope.row.enabled === 1 ? 'success' : 'danger'">{{ scope.row.enabled === 1 ? '启用' : '禁用' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="priority" label="优先级" width="100px" />
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="scope">
                  <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
                  <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-row>
        <el-row>
          <div class="common-div-card rs-pagination">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 30, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              background
            />
          </div>
        </el-row>
      </el-main>
    </el-container>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="formData" label-width="120px">
        <el-form-item label="钢种">
          <el-input v-model="formData.gradeStr" placeholder="请输入钢种" />
        </el-form-item>
        <el-form-item label="最小宽度(mm)">
          <el-input-number v-model="formData.minWidth" :min="0" :controls="false" style="width:100%" />
        </el-form-item>
        <el-form-item label="最大宽度(mm)">
          <el-input-number v-model="formData.maxWidth" :min="0" :controls="false" style="width:100%" />
        </el-form-item>
        <el-form-item label="最大包含">
          <el-radio-group v-model="formData.maxInclusive">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="切边条件">
          <el-radio-group v-model="formData.edgeTrimCond">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="合同号">
          <el-input v-model="formData.contractStr" placeholder="请输入合同号" />
        </el-form-item>
        <el-form-item label="排除合同号">
          <el-input v-model="formData.excludeContractStr" placeholder="请输入排除合同号" />
        </el-form-item>
        <el-form-item label="等级">
          <el-input v-model="formData.levelStr" placeholder="请输入等级" />
        </el-form-item>
        <el-form-item label="速度限制">
          <el-input-number v-model="formData.speedLimit" :min="0" :controls="false" style="width:100%" />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-radio-group v-model="formData.enabled">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优先级">
          <el-input-number v-model="formData.priority" :min="0" :controls="false" style="width:100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { acidRollingApi } from '/@/api/acidRollingProductionEfficiency/index';

// 查询表单接口
interface SearchForm {
  gradeStr: string; // 钢种
}

// 速度规则数据接口
interface SpeedRuleData {
  id?: number;
  gradeStr: string;
  minWidth: number;
  maxWidth: number;
  maxInclusive: number;
  edgeTrimCond: number;
  contractStr: string;
  excludeContractStr: string;
  levelStr: string;
  speedLimit: number;
  enabled: number;
  priority: number;
}

const headerSearchForm = reactive<SearchForm>({
  gradeStr: '',
});

// 表格数据
const tableData = ref<SpeedRuleData[]>([]);
const tableLoading = ref(false);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 30,
  total: 0,
});

// 弹窗相关
const dialogVisible = ref<boolean>(false);
const dialogTitle = ref<string>('新增速度规则');
const formData = reactive<SpeedRuleData>({
  gradeStr: '',
  minWidth: 0,
  maxWidth: 0,
  maxInclusive: 0,
  edgeTrimCond: 0,
  contractStr: '',
  excludeContractStr: '',
  levelStr: '',
  speedLimit: 0,
  enabled: 1,
  priority: 0,
});

// 获取表格数据
const fetchTableData = async () => {
  try {
    tableLoading.value = true;
    const params: any = {
      pageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
      gradeStr: headerSearchForm.gradeStr || undefined,
    };

    // 移除未定义的参数
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key];
      }
    });

    const response = await acidRollingApi.tcmPlSpeedRulesPage(params);
    console.log('API Response:', response);

    const responseData = response.data;
    if (responseData && responseData.data && Array.isArray(responseData.data)) {
      tableData.value = responseData.data;
      pagination.total = responseData.count || responseData.data.length;
      ElMessage.success(responseData.msg || '查询成功');
    } else {
      ElMessage.info(responseData?.msg || '未查询到数据或响应格式不正确');
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error: any) {
    console.error('获取数据失败:', error);
    const errorMessage = error.response?.data?.msg || error.msg || error.message || '获取数据失败';
    ElMessage.error(errorMessage);
    tableData.value = [];
    pagination.total = 0;
  } finally {
    tableLoading.value = false;
  }
};

// 查询方法
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchTableData();
};

// 重置方法
const handleReset = () => {
  headerSearchForm.gradeStr = '';
  handleSearch();
};

// 新增按钮
const handleAdd = () => {
  dialogTitle.value = '新增速度规则';
  Object.assign(formData, {
    id: undefined,
    gradeStr: '',
    minWidth: 0,
    maxWidth: 0,
    maxInclusive: 0,
    edgeTrimCond: 0,
    contractStr: '',
    excludeContractStr: '',
    levelStr: '',
    speedLimit: 0,
    enabled: 1,
    priority: 0,
  });
  dialogVisible.value = true;
};

// 编辑按钮
const handleEdit = (row: SpeedRuleData) => {
  dialogTitle.value = '编辑速度规则';
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 删除按钮
const handleDelete = async (row: SpeedRuleData) => {
  try {
    await ElMessageBox.confirm('确认删除该条数据吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    const response = await acidRollingApi.tcmPlSpeedRulesDelete({ id: row.id });
    console.log('Delete Response:', response);
    // 兼容多种响应格式: code === 1 或 data === "SUCCESS" 或 msg === "SUCCESS"
    if (response.data.code === 1 || response.data.data === 'SUCCESS' || response.data.msg === 'SUCCESS') {
      ElMessage.success('删除成功');
      await fetchTableData();
    } else {
      ElMessage.error(response.data.msg || '删除失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error(error.response?.data?.msg || error.msg || '删除失败');
    }
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    if (formData.id) {
      // 编辑
      const response = await acidRollingApi.tcmPlSpeedRulesUpdate(formData);
      console.log('Update Response:', response);
      // 兼容多种响应格式: code === 1 或 data === "SUCCESS" 或 msg === "SUCCESS"
      if (response.data.code === 1 || response.data.data === 'SUCCESS' || response.data.msg === 'SUCCESS') {
        ElMessage.success('修改成功');
        dialogVisible.value = false;
        await fetchTableData();
      } else {
        ElMessage.error(response.data.msg || '修改失败');
      }
    } else {
      // 新增
      const response = await acidRollingApi.tcmPlSpeedRulesAdd(formData);
      console.log('Add Response:', response);
      // 兼容多种响应格式: code === 1 或 data === "SUCCESS" 或 msg === "SUCCESS"
      if (response.data.code === 1 || response.data.data === 'SUCCESS' || response.data.msg === 'SUCCESS') {
        ElMessage.success('新增成功');
        dialogVisible.value = false;
        await fetchTableData();
      } else {
        ElMessage.error(response.data.msg || '新增失败');
      }
    }
  } catch (error: any) {
    console.error('提交失败:', error);
    ElMessage.error(error.response?.data?.msg || error.msg || '操作失败');
  }
};

// 分页大小变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  fetchTableData();
};

// 页码变化
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchTableData();
};

// 生命周期钩子
onMounted(() => {
  fetchTableData(); // 组件挂载时获取初始数据
});
</script>

<style scoped lang="less">
@border-radius: 8px;
@primary-color: #2c69e8;
@box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
@box-shadow-hover: 0 8px 32px rgba(0, 0, 0, 0.12);
@border: 1px solid #dcdfe6;

.rolling-speed {
  width: 100%;
  height: 100vh;
  position: relative;
  background-color: #fff;
  overflow: auto;
  margin-bottom: 1vw;
}

.common-div-card {
  box-shadow: @box-shadow;
  transition: 0.3s;
  border-radius: @border-radius;
  border: @border;

  // 悬停状态
  &:hover {
    box-shadow: @box-shadow-hover;
  }
}

.rs-header {
  display: flex;
  flex: 1;
  justify-content: flex-start;
  align-items: center;
  padding: 20px;
  height: 10vh;
}

.rs-header-form {
  display: flex;
  align-items: center;
  gap: 20px;
}

.rs-table {
  width: 100%;
  height: 60vh;
  padding: 10px;
  margin-top: -1vh;

  .el-table {
    height: calc(60vh - 20px);
  }
}

.rs-pagination {
  width: 100%;
  height: 6vh;
  display: flex;
  justify-content: flex-end;
  padding: 20px;
}
</style>
